<?php
class Controller_Pc_Api_V2_Guide_Member extends Controller_Pc_Api_V2_Base
{
    protected $member_id;


    protected $request_param;

    protected $type_id;

    protected $guide;

    public function before()
    {
        parent::before();
        $this->request_param = array_map(function ($item) {
            return Common::remove_xss($item);
        }, (array)$this->request_data);
        $this->type_id = 106;
        $check_token = Model_Api_v2_Pub::token_decode($this->request_param['token']);
        $this->member_id = $check_token['status'] ? $check_token['mid'] : 0;
        if (empty($this->member_id)) {
            $this->send_datagrams($this->client_info['id'], array('status' => false, 'msg' => __('用户未登录')), $this->client_info['secret_key']);
            exit;
        }
    }

    /**
     * 获取导游信息
     */
    public function action_guide_info()
    {
        $row = DB::select()->from('guide')->where('mid', '=', $this->member_id)->execute()->current();
        $row['litpic'] = Model_Api_V2_System::uniapp_img($row['litpic']);
        $this->result = array('status'=>true,'data'=> $row);
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);

    }


    /**
     * 会员否是导游
     */
    public function action_is_guide(){
        if (!St_Functions::is_normal_app_install('system_guide')) {
            $this->result = array('status' => true, 'data' => '');
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
        $memberid = $this->member_id;
        $guide = DB::select()->from('guide')
            ->where('mid', '=', $memberid)
            ->where('status', '=', 1)
            ->execute()
            ->current();
        if (empty($guide)) {
            $this->result = array('status' => true, 'msg' => '操作成功','data'=>['is_guide'=>0,'msg'=>'未开通导游/认证未通过']);
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
        $guide['litpic'] = Model_Api_V2_System::uniapp_img($guide['litpic']);
        $guide['is_guide']=1;
        $this->result = array('status' => true, 'msg' => '操作成功', 'data' => $guide);
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    //提交导游认证
    public function action_certify(){
        $guide_code = $this->request_data->guide_code;
        $guide_pic = $this->request_data->guide_pic;
        if(empty($guide_code)){
            $this->result = array('status'=>false,'data'=> '请填写导游证号');
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
        if(empty($guide_pic)){
            $this->result = array('status'=>false,'data'=> '请上传导游证照片');
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
        $memberid = $this->member_id;
        $member = DB::select()->from('member')->where('mid','=',$memberid)->execute()->current();
        if($member['verifystatus']!=2){
            $this->result = array('status'=>false,'data'=> '请先实名认证');
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }
        list($guide) = Model_Guide::get_info($memberid, 'guide');
        $data = DB::select()->from('guide')->where('id', '=', $guide['id'])->execute()->current();
        $updata = array(
            'title' => $member['truename'],
            'mobile' => $member['mobile'],
            'litpic' => $member['litpic'],
            'guide_card_id' => $guide_code,
            'guide_card_pic' => substr($guide_pic, strpos($guide_pic, "/upload")),
            'mid'=>$memberid,
            'status'=>3,
            'addtime'=>time()
        );
        if ($data) {
            DB::update('guide')->set($updata)->where('id', '=', $data['id'])->execute();
        } else {
            DB::insert('guide', array_keys($updata))->values(array_values($updata))->execute();
        }
        $this->result = array('status' => true, 'data' =>'提交成功' );
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    //导游认证状态
    public function action_certify_status(){
        $memberid = $this->member_id;
        list($guide) = Model_Guide::get_info($memberid, 'guide');
        $data = DB::select()->from('guide')->where('id', '=', $guide['id'])->execute()->current();
        if($data){
            $this->result = array('status' => true, 'data' =>$data['status'] );
        }else{
            $this->result = array('status' => false, 'data' =>-1 );
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 获取导游邀请码
     */
    public function action_get_qrcode()
    {
        $memberid = $this->member_id;
        $guide = DB::select('guide_qrcode')->from('guide')->where('mid', '=', $memberid)->execute()->current();
        if($guide['guide_qrcode'])
        {
            $guide['guide_qrcode'] = Model_Api_V2_System::uniapp_img($guide['guide_qrcode']);
            $this->result = array('status' => true, 'data' => $guide,'mid'=>$memberid);
        }
        else
        {
            $this->result = array('status' => false, 'msg' => __('未生成导游码'),'member_id'=>$memberid);
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }


    /**
     * 带团记录
     */
    public function action_record()
    {
        try {
            //会员id
            $member_id = $this->request_param['member_id'] ? $this->request_param['member_id'] : $this->member_id;
            $validataion = Validation::factory($this->request_param);
            $validataion->rule('page', 'not_empty');
            $validataion->rule('pagesize', 'not_empty');
            if (!$validataion->check()) {
                $error = $validataion->errors();
                $keys = array_keys($validataion->errors());
                throw new Exception(__("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            }
            $guide =$this->_get_guide($member_id);
            $offset = ($this->request_param['page'] - 1) * $this->request_param['pagesize'];
            $w = " where b.guide_id={$guide['id']} ";
            if (!empty($keyword)) {
                $w .= " and a.ordersn='{$keyword}' ";
            }
            $order = " order by addtime desc ";
            $fields = "a.ordersn,a.productname,a.linkman,a.litpic,a.status,a.productautoid,a.typeid,a.addtime,a.usedate";
            $fields .= ",b.people_num,b.start_time,b.end_time,b.award";

            $sql = " select {$fields} from sline_member_order a left join sline_guide_order b on a.ordersn=b.ordersn {$w}  {$order} limit {$offset},{$this->request_param['pagesize']} ";
            $total = " select count(a.id) as total  from sline_member_order a left join sline_guide_order b on a.ordersn=b.ordersn {$w}  {$order}";
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            $total = DB::query(Database::SELECT, $total)->execute()->current();

            foreach ($list as &$v) {
                $productInfo = St_Product::get_product_info($v['typeid'], $v['productautoid']);
                $v['litpic'] = Model_Api_V2_System::uniapp_img($productInfo['litpic']);
                $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
                $v['status_name'] = Model_Guide::get_order_status_name($v['status']);
                $v['guide'] = $guide['title'];
                $v['start_time'] = $v['start_time'] ? date('Y-m-d H:i:s',$v['start_time']) : '';
                $v['end_time'] = $v['end_time'] ? date('Y-m-d H:i:s',$v['end_time']) : '';
            }
            $this->result = array('status' => true, 'data' => array('total' => $total['total'], 'list' => $list));
        } catch (Exception $e) {
            $this->result = array('status' => false, 'msg' => $e->getMessage());
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 扫码
     */
    public function action_scan_code()
    {
        $code = $this->request_data->code;
        //会员id
        $member_id = $this->member_id;
        try{
            if(!$code)
            {
                throw new Exception(__('消费码不能为空'));
            }
            $guide = $this->_get_guide($member_id);
            $order = DB::select()->from('member_order')
                ->where('eticketno','=',$code)
                ->where_open()
                ->where('status','=',2)
                ->or_where('status','=',9)
                ->where_close()
                ->execute()
                ->current();
            if(!isset($order['id']))
            {
                throw new Exception(__('未找到订单'));
            }
            $guide_order = DB::select()->from('guide_order')
                ->where('ordersn','=',$order['ordersn'])
                ->and_where('guide_id','=',$guide['id'])
                ->execute()
                ->current();
            $result = array(
                'ordersn' => $order['ordersn'],
                'title' => $order['productname'],
                'usedate' => $order['usedate'],
                'guide' => $guide['title'],
                'code' => $code,
                'tourer' => $order['linkman'],
                'status' => $order['status']
            );
            if($guide_order['start_time'])
            {
                $result['start_time'] = date('Y-m-d H:i:s',$guide_order['start_time']);
            }
            if($guide_order['end_time'])
            {
                $result['end_time'] = date('Y-m-d H:i:s',$guide_order['end_time']);
            }
            if(!isset($guide_order['id']))
            {
                throw new Exception(__('此订单你不能接单'));
            }

            $this->result = array('status'=>true,'data'=>$result);

        }catch(Exception $ex){
            $this->result = array('status' => false, 'msg' => $ex->getMessage());
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);


    }

    /**
     * 开始接单
     */
    public function action_start_service()
    {
        $db = Database::instance();
        $db->begin();
        try{
            //会员id
            $member_id = $this->request_param['member_id'] ? $this->request_param['member_id'] : $this->member_id;
            $guide = $this->_get_guide($member_id);
            $ordersn = $this->request_data->ordersn;
            if(!$ordersn)
            {
                throw new Exception(__('订单号不能为空'));
            }

            $guide_order = DB::select()->from('guide_order')
                ->where('ordersn','=',$ordersn)
                ->and_where('guide_id','=',$guide['id'])
                ->execute()->current();
            if(!isset($guide_order['id']))
            {
                throw new Exception(__('未找到订单'));
            }
            $order = Model_Member_Order::order_info($ordersn);
            if($order['status'] != 2 )
            {
                throw new Exception(__('接单失败,此订单为非待接单状态'));
            }
            //时间判断
            $usedate = strtotime($order['usedate']);
            if($usedate != strtotime(date('Y-m-d')))
            {
                throw new Exception(__('结单失败,服务日期有误'));
            }
            //更新订单状态
            DB::update('member_order')->set(array('status'=>9))->where('ordersn','=',$ordersn)->execute();
            //更新服务开始时间
            DB::update('guide_order')->set(array('start_time'=>time()))->where('ordersn','=',$ordersn)->execute();
            $this->result = array('status' => true,'msg'=>'接单成功');
            $db->commit();

        }catch(Exception $ex) {
            $db->rollback();
            $this->result = array('status' => false, 'msg' => $ex->getMessage());

        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 结束接单
     */
    public function action_end_service()
    {
        $db = Database::instance();
        $db->begin();
        try{
            //会员id
            $member_id = $this->request_param['member_id'] ? $this->request_param['member_id'] : $this->member_id;
            $guide = $this->_get_guide($member_id);
            $ordersn = $this->request_data->ordersn;
            if(!$ordersn)
            {
                throw new Exception(__('订单号不能为空'));
            }
            $guide_order = DB::select()->from('guide_order')
                ->where('ordersn','=',$ordersn)
                ->and_where('guide_id','=',$guide['id'])
                ->execute()->current();
            if(!isset($guide_order['id']))
            {
                $this->send_datagrams($this->client_info['id'], array('status' => false, 'msg' => __('未找到订单')), $this->client_info['secret_key']);
            }
            $order = Model_Member_Order::order_info($ordersn);
            if($order['status'] != 9 )
            {
                throw new Exception(__('接单失败,此订单为非服务中状态'));
            }
            Model_Guide::end_service($ordersn);
            $this->result = array('status' => true,'msg'=>'操作成功');
            $db->commit();

        }catch(Exception $ex) {
            $db->rollback();
            $this->result = array('status' => false, 'msg' => $ex->getMessage());

        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);

    }

    /**
     * 获取进行中的服务
     */
    public function action_get_guide_current_service()
    {
        $memberid = $this->member_id;
        $guide = DB::select()->from('guide')->where('mid', '=', $memberid)->execute()->current();
        $order = DB::select()->from('guide_order')
            ->where('guide_id','=',$guide['id'])
            ->and_where('start_time','>',0)
            ->and_where('end_time','=',0)
            ->execute()
            ->current();
        if(isset($order['id']))
        {
            $member_order = Model_Member_Order::order_info($order['ordersn']);
            $result = array(
                'ordersn' => $order['ordersn'],
                'title' => $member_order['productname'],
                'usedate' => $member_order['usedate'],
                'guide' => $guide['title'],
                'code' => $member_order['eticketno'],
                'tourer' => $member_order['linkman'],
                'status' => $member_order['status']
            );
            if($order['start_time'])
            {
                $result['start_time'] = date('Y-m-d H:i:s',$order['start_time']);
            }
            $this->result = array('status'=>true,'data'=>$result);
        }
        else
        {
            $this->result = array('status' => false, 'msg' => '未找到进行中的服务');
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);

    }
    //获取导游信息
    function _get_guide($member_id)
    {
        $guide =DB::select()->from('guide')->where('mid','=',$member_id)->execute()->current();
        if(!isset($guide['id']))
        {
            throw new Exception(__("导游信息有误"));
        }
        return $guide;
    }


}
